package com.robot.core;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import com.robot.bean.Reply;
import com.robot.util.TextUtils;

public class Source {
	private Map<String,Reply> replys = new HashMap<String,Reply>();
	private List<String> idioms = new ArrayList<String>();
	private Map<Long,String> notices = new HashMap<Long,String>();
	public Source() {
		init();
	}
	public static void main(String[] args) {
		new Source();
	}
	/**
	 * 
	 */
	private void init() {
		String userPath = System.getProperty("user.dir");
		loadReplys(new File(new File(userPath),"source/library"));
		loadIdiom(new File(new File(userPath),"source/idiom"));
		System.out.println("成功加载回复词条："+replys.size());
		System.out.println("成功加载成语词条："+idioms.size());
	}

	/**
	 * @param dir
	 */
	private void loadIdiom(File dir) {		
		for(File file:dir.listFiles()){
			List<String> lines = TextUtils.readLine(file.getAbsolutePath(),"UTF-8");
			for(String line:lines){
				if(Pattern.matches("\\S+", line)){
					idioms.add(line.trim());					
				}
			}
		}
	}

	/**
	 * @param dir
	 */
	private void loadReplys(File dir) {
		Reply reply = new Reply();
		for(File file:dir.listFiles()){
			List<String> lines = TextUtils.readLine(file.getAbsolutePath(),"GBK");
			int index = 0;
			for(String line:lines){
				if(Pattern.matches("^ *$", line)){
					index = 0;
					continue;
				}
				if(index==0){
					reply = replys.get(line);
					if(reply==null){
						reply = new Reply();
					}
					reply.setQuestion(line);
					index ++;
				}else if(index==1){
					reply.setAnswer(line);					
					replys.put(reply.getQuestion(),reply);				
				}
			}
		}
	}
	
	/**
	 * @param key
	 * @return 智能回复
	 */
	public String getAnswer(String key){
		Reply reply = this.replys.get(key);
		if(reply!=null){
			return reply.getAnswer();			
		}else{
			return null;
		}
	}
	public List<String> getIdioms() {
		return idioms;
	}
	public void setIdioms(List<String> idioms) {
		this.idioms = idioms;
	}
	public void putNotice(Long time,String msg) {
		this.notices.put(time, msg);
	}
	public String getNotice(Long time){
		String msg = null;
		for(Long key:this.notices.keySet()){
			if(time>key){
				msg = this.notices.remove(key);
				break;
			}
		}
		return msg;
	}
}
